---
import HeaderLink from './HeaderLink.astro'
---

<dropdown-menu>
  <div
    data-dropdown="false"
    id="dropdown-menu"
    role="menu"
    class="absolute top-full right-0 mt-2 w-64 divide-y divide-stone-200 overflow-hidden rounded-lg border border-stone-300 bg-white py-1 shadow-lg data-[dropdown=false]:hidden data-[dropdown=true]:block"
  >
    <HeaderLink class="block px-4 py-2 focus:ring-inset" href="/components/application">
      Application
    </HeaderLink>

    <HeaderLink class="block px-4 py-2 focus:ring-inset" href="/components/marketing">
      Marketing
    </HeaderLink>

    <HeaderLink class="block px-4 py-2 focus:ring-inset" href="/blog">Blog</HeaderLink>
  </div>
</dropdown-menu>

<script>
  class DropdownMenu extends HTMLElement {
    private toggleHandler: ((event: Event) => void) | null = null

    connectedCallback() {
      const dropdownEl = this.querySelector('[data-dropdown]') as HTMLDivElement | null

      if (!dropdownEl) {
        return
      }

      this.toggleHandler = (toggleEvent: Event) => {
        const isOpen = (toggleEvent as CustomEvent).detail.open

        dropdownEl.setAttribute('data-dropdown', isOpen ? 'true' : 'false')
      }

      document.addEventListener('dropdown:toggle', this.toggleHandler)
    }

    disconnectedCallback() {
      if (this.toggleHandler) {
        document.removeEventListener('dropdown:toggle', this.toggleHandler)

        this.toggleHandler = null
      }
    }
  }

  customElements.define('dropdown-menu', DropdownMenu)
</script>
